package com.ztgf.order.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.db.utils.RedisUtil;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.constant.OrderConstant;
import com.ztgf.order.mapper.OrderContractParamRelationMapper;
import com.ztgf.order.models.bo.OrderContractParamRelationSaveBO;
import com.ztgf.order.models.bo.OrderInvoiceBO;
import com.ztgf.order.models.dto.OrderContractParamRelationDTO;
import com.ztgf.order.models.dto.OrderInfoDTO;
import com.ztgf.order.models.dto.OrderPaymentTypeDTO;
import com.ztgf.order.models.service.*;
import com.ztgf.order.models.vo.OrderCommodityDetailVO;
import com.ztgf.order.models.vo.OrderInfoVO;
import com.ztgf.pay.models.dto.PayUserDTO;
import com.ztgf.pay.models.service.IPayUserService;
import com.ztgf.shopping.models.dto.shop.ShopContractParamRelationDTO;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.service.shop.IShopContractParamRelationService;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.shopping.models.vo.shop.ShopInfoUserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单合同的参数关系表控制器
 *
 * @author YUE
 * @Date 2020-07-20 17:48:20
 */
@DubboService
@Slf4j
@Lazy
public class OrderContractParamRelationServiceImpl extends ServiceImpl<OrderContractParamRelationMapper, OrderContractParamRelationDTO> implements IOrderContractParamRelationService{

    @Resource
    private YmlConfig ymlConfig;

    @DubboReference
    private IShopInfoService shopInfoService;

    @Autowired
    private IOrderContractRelationService orderContractRelationService;

    @Autowired
    private IOrderInvoiceService orderInvoiceService;

    @Autowired
    private IOrderStatusService orderStatusService;

    @DubboReference
    private IShopContractParamRelationService shopContractParamRelationService;

    @DubboReference
    private IPayUserService payUserService;

    @DubboReference
    private IOrderPaymentTypeService orderPaymentTypeService;

    @Autowired
    private RedisUtil redisUtil;

    @DubboReference
    private IOrderInfoService orderInfoService;

    @Override
    public boolean add(OrderContractParamRelationSaveBO saveBO) {
        OrderContractParamRelationDTO dto = new OrderContractParamRelationDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    /**
     * 根据订单id查询
     * @param orderId
     * @return
     */
    @Override
    public OrderContractParamRelationDTO getByOrderId(Long orderId){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("order_id", orderId);
        return selectOne(wrapper);
    }

    /**
     * 下单时 添加默认的合同参数
     * @param orderInfoVO
     * @param orderInvoiceBO
     * @return
     */
    public boolean addDefaultContent(OrderInfoVO orderInfoVO, OrderInvoiceBO orderInvoiceBO, List<String> ids) {
        OrderContractParamRelationDTO dto = new OrderContractParamRelationDTO();
        Long buyerId = orderInfoVO.getBuyerShopId();
        Long sellId = orderInfoVO.getSellShopId();
        ShopContractParamRelationDTO shopContractParamRelationDTO = shopContractParamRelationService.getByShopIdAndType(sellId, orderInfoVO.getPayType());
        if(null == shopContractParamRelationDTO){
            log.error(sellId + "：此店铺没有合同模板");
            throw new RuntimeException(sellId + "此店铺没有合同模");
        }
        BeanUtils.copyProperties(shopContractParamRelationDTO,dto);
        Long orderId = orderInfoVO.getId();
        dto.setOrderId(orderId);//订单id
        dto.setType(orderInfoVO.getPayType());//订单类型
        if(null != orderInvoiceBO){//税率
            if(orderInvoiceBO.getType() == 0){//纸质发票
                //dto.setTaxRate(0.13);
                dto.setInvoceType(1);
            }else{//电子发票
                //dto.setTaxRate(0.06);
                dto.setInvoceType(0);
            }
        }
        if(orderInfoVO.getPayType() == 1){//预售
            BigDecimal actualMoney = orderInfoVO.getActualMoney();//应负总价
            OrderCommodityDetailVO orderCommodityDetailVO = orderInfoVO.getOrderCommodityDetailVOList().get(0);
            Integer firstBalance = orderCommodityDetailVO.getFirstBalance();
            Integer tailBalance = orderCommodityDetailVO.getTailBalance();
            BigDecimal firstMoney = actualMoney.multiply(new BigDecimal(firstBalance).divide(new BigDecimal(100)));
            BigDecimal tailMoney = actualMoney.multiply(new BigDecimal(tailBalance).divide(new BigDecimal(100)));

            dto.setFirstBalance(firstBalance);
            dto.setTailBalance(tailBalance);
            dto.setFirstMoney(firstMoney);
            dto.setTailMoney(tailMoney);

        }
        ShopInfoDTO buyerShopInfoDTO = shopInfoService.selectById(buyerId);
        ShopInfoDTO sellerShopInfoDTO = shopInfoService.selectById(sellId);
        PayUserDTO buyPayUserDTO = payUserService.getPayUserDTO(orderInfoVO.getBuyerShopId(),1);
        PayUserDTO sellPayUserDTO = payUserService.getPayUserDTO(orderInfoVO.getSellShopId(),1);
        StringBuilder stringBuffer = new StringBuilder("ZTGF");//最终的合同编号
        String str = "00000000";//暂定8位
        String yearMonthDayHourMinute = DateUtils.dateToStr(new Date(), DateUtils.DATE_FORMAT_DATEHH);//年月日时分秒
        Long orderContactNo = redisUtil.getOrderContactNo();
        String substring = str.substring(0, str.length() - orderContactNo.toString().length()) + orderContactNo;//合同尾号
        stringBuffer.append(yearMonthDayHourMinute);
        stringBuffer.append(substring);
        dto.setContractNo(stringBuffer.toString());//合同编号
//        ShopInfoDTO buyShopInfoDTO = shopInfoService.selectById(orderInfoVO.getBuyerShopId());
        dto.setJiaOpenBank(buyPayUserDTO.getZjBankName());
        dto.setJiaOpenAccount(buyPayUserDTO.getZjBankElectronicNo());
        dto.setJiaCompanyName(buyerShopInfoDTO.getName());
        dto.setJiaLegalPerson(buyerShopInfoDTO.getLegalPerson());
        dto.setJiaCompanyAddress(buyerShopInfoDTO.getAddress());
        dto.setJiaCreditCode(buyerShopInfoDTO.getCreditCode());
        ShopInfoUserVO jiaUser = shopInfoService.getUser(buyerId);
        dto.setJiaPhone(jiaUser.getMobile());
        dto.setJiaContacter(jiaUser.getContactName());
        dto.setJiaEmail(jiaUser.getEmail());

//        ShopInfoDTO sellShopInfoDTO = shopInfoService.selectById(orderInfoVO.getSellShopId());
        dto.setYiOpenBank(sellPayUserDTO.getZjBankName());
        dto.setYiOpenAccount(sellPayUserDTO.getZjBankElectronicNo());
        dto.setYiCompanyName(sellerShopInfoDTO.getName());
        dto.setYiLegalPerson(sellerShopInfoDTO.getLegalPerson());
        dto.setYiCompanyAddress(sellerShopInfoDTO.getAddress());
        dto.setYiCreditCode(sellerShopInfoDTO.getCreditCode());
        ShopInfoUserVO yiUser = shopInfoService.getUser(sellId);
        dto.setYiPhone(yiUser.getMobile());
        dto.setYiContacter(yiUser.getContactName());
        dto.setYiEmail(yiUser.getEmail());
        dto.setOrderCommodityIds(ids.stream().collect(Collectors.joining(",")));
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }


    /**
     * 用户确认赊销，修改合同类型
     * @param orderId
     * @return
     */
    public boolean updateDefaultContent(Long orderId) {
        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
        if(null  == orderInfoDTO){
            return false;
        }
        //获取订单合同
        OrderContractParamRelationDTO dto =  this.getByOrderId(orderInfoDTO.getId());
        //获取订单是否确认为赊销
        Wrapper<OrderPaymentTypeDTO> orderPaymentTypeDTOWrapper = new EntityWrapper<>();
        orderPaymentTypeDTOWrapper.eq("order_id",orderInfoDTO.getId());
        List<OrderPaymentTypeDTO> orderPaymentTypeDTOList = orderPaymentTypeService.selectList(orderPaymentTypeDTOWrapper);
        if(CustomizeUtil.listIsNotNull(orderPaymentTypeDTOList)){
            for(OrderPaymentTypeDTO orderPaymentTypeDTO : orderPaymentTypeDTOList){
                //用户设置的支付类型为赊销
                if(orderPaymentTypeDTO.getPaymentType() == OrderConstant.ORDER_PAYMENT_TYPE_CREDIT && orderPaymentTypeDTO.getType() == 1){
                    //获取店铺合同模板
                    ShopContractParamRelationDTO shopContractParamRelationDTO = shopContractParamRelationService.getByShopIdAndType(orderInfoDTO.getSellShopId(), orderPaymentTypeDTO.getPaymentType());
                    if(null == shopContractParamRelationDTO){
                        log.error(orderInfoDTO.getSellShopId() + "：此店铺没有合同模板");
                        throw new RuntimeException(orderInfoDTO.getSellShopId() + "此店铺没有合同模");
                    }
                    BeanUtils.copyProperties(shopContractParamRelationDTO,dto,new String[]{"id"});
                    return this.updateById(dto);
                }
            }
        }
        return true;
    }


    /**
     * 获取赊销合同模板
     * @param orderId
     * @return
     */
    public ShopContractParamRelationDTO getContractContent(Long orderId) {
        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
        if(null  == orderInfoDTO){
            return null;
        }
        //获取订单合同
        OrderContractParamRelationDTO dto =  this.getByOrderId(orderInfoDTO.getId());
        //获取订单是否确认为赊销
        Wrapper<OrderPaymentTypeDTO> orderPaymentTypeDTOWrapper = new EntityWrapper<>();
        orderPaymentTypeDTOWrapper.eq("order_id",orderInfoDTO.getId());
        List<OrderPaymentTypeDTO> orderPaymentTypeDTOList = orderPaymentTypeService.selectList(orderPaymentTypeDTOWrapper);
        if(CustomizeUtil.listIsNotNull(orderPaymentTypeDTOList)){
            for(OrderPaymentTypeDTO orderPaymentTypeDTO : orderPaymentTypeDTOList){
                //用户设置的支付类型为赊销
                if(orderPaymentTypeDTO.getPaymentType() == OrderConstant.ORDER_PAYMENT_TYPE_CREDIT && orderPaymentTypeDTO.getType() == 1){
                    //获取店铺合同模板
                    ShopContractParamRelationDTO shopContractParamRelationDTO = shopContractParamRelationService.getByShopIdAndType(orderInfoDTO.getSellShopId(), orderPaymentTypeDTO.getPaymentType());
                    return shopContractParamRelationDTO;
                }
            }
        }
        return  null;
    }

}
